import {
    Button,
    Input,
    Modal,
    ModalBody,
    ModalContent,
    ModalFooter,
    ModalHeader,
    Textarea,
    useDisclosure,
    Image,
    Spinner
} from "@nextui-org/react";
import React, { useEffect, useRef, useState } from "react";
import { BiFolderOpen, BiLabel, BiUpload, BiX } from "react-icons/bi";
import createAxiosClient from "@/app/utils/axiosRequest";
import ToastUtil from "@/app/utils/toastUtil";
import EmojiSelect from "@/app/components/tools/EmojiSelect";
import PubSub from "pubsub-js";

/**
 * 修改文件夹组件
 * @param isOpen 是否打开
 * @param onOpenChange 打开状态改变回调
 * @param folderId 文件夹ID
 * @constructor
 */
export default function UpdateFolder({ isOpen, onOpenChange, folderId }: any) {
    // axios接口
    const axiosInstance = createAxiosClient();
    // 加载状态
    const [loading, setLoading] = useState(false);
    // Emoji
    const [emoji, setEmoji] = useState('📂');
    // 选择表情
    const { isOpen: isSelectEmoji, onOpen: onOpenSelectEmoji, onOpenChange: onSelectChange } = useDisclosure();
    // 文件夹数据
    const [folderData, setFolderData] = useState({
        id: 0,
        name: '',
        description: '',
        icon: '',
        parentId: null as number | null
    });

    // 文件上传相关状态
    const [uploading, setUploading] = useState(false);
    const [previewUrl, setPreviewUrl] = useState('');
    const fileInputRef = useRef<HTMLInputElement>(null);

    // 获取文件夹详情
    useEffect(() => {
        if (isOpen && folderId) {
            fetchFolderDetails();
        }
    }, [isOpen, folderId]);

    // 获取文件夹详情
    const fetchFolderDetails = async () => {
        if (!folderId) return;

        setLoading(true);
        try {
            const response = await axiosInstance.get(`/app/collection/${folderId}`);
            const data = response.data;
            
            if (data.status && data.data) {
                const folder = data.data;
                setFolderData({
                    id: folder.id,
                    name: folder.name || '',
                    description: folder.description || '',
                    icon: folder.icon || '',
                    parentId: folder.parentId
                });
                
                // 设置emoji
                if (folder.emoji) {
                    setEmoji(folder.emoji);
                }
                
                // 设置预览URL
                if (folder.icon) {
                    setPreviewUrl(folder.icon);
                }
            } else {
                ToastUtil(data.message || "获取文件夹信息失败", '❌', "error");
            }
        } catch (error: any) {
            ToastUtil(error.message || "获取文件夹信息异常", '❌', "error");
        } finally {
            setLoading(false);
        }
    };

    // 上传文件处理函数
    const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        if (!file) return;
        
        // 验证文件类型，只允许图片
        if (!file.type.startsWith('image/')) {
            ToastUtil("请上传图片文件", '❌', "error");
            return;
        }
        
        // 显示本地预览
        const localPreviewUrl = URL.createObjectURL(file);
        setPreviewUrl(localPreviewUrl);
        
        // 准备上传
        setUploading(true);
        
        try {
            // 创建FormData
            const formData = new FormData();
            formData.append('file', file);
            
            // 业务ID可以是文件夹ID
            const tempBusinessId = `folder-${folderData.id || Date.now()}`;
            
            // 调用文件上传接口
            const response = await axiosInstance.post(`/middleware/file/upload?businessId=${tempBusinessId}`, 
                formData, 
                {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                }
            );
            
            const data = response.data;
            if (data.status && data.data) {
                // 确保只存储URL字符串
                const iconUrl = data.data.url || data.data;
                setFolderData({
                    ...folderData,
                    icon: iconUrl
                });
                ToastUtil("图标上传成功", '✅', "success");
            } else {
                ToastUtil(data.message || "上传失败", '❌', "error");
                // 清除预览，如果是新上传的
                if (localPreviewUrl !== previewUrl) {
                    URL.revokeObjectURL(localPreviewUrl);
                    // 如果有旧预览，恢复旧预览
                    if (folderData.icon) {
                        setPreviewUrl(folderData.icon);
                    } else {
                        setPreviewUrl('');
                    }
                }
            }
        } catch (error: any) {
            ToastUtil(error.message || "上传异常", '❌', "error");
            // 清除预览，如果是新上传的
            if (localPreviewUrl !== previewUrl) {
                URL.revokeObjectURL(localPreviewUrl);
                // 如果有旧预览，恢复旧预览
                if (folderData.icon) {
                    setPreviewUrl(folderData.icon);
                } else {
                    setPreviewUrl('');
                }
            }
        } finally {
            setUploading(false);
        }
    };

    // 清除已上传的图标
    const clearUploadedIcon = () => {
        setFolderData({
            ...folderData,
            icon: ''
        });
        if (previewUrl) {
            // 如果是本地预览URL，需要释放
            if (previewUrl.startsWith('blob:')) {
                URL.revokeObjectURL(previewUrl);
            }
            setPreviewUrl('');
        }
        if (fileInputRef.current) {
            fileInputRef.current.value = '';
        }
    };

    // 更新文件夹
    const updateFolder = async () => {
        try {
            const response = await axiosInstance.put(`/app/collection/${folderData.id}`, {
                "id": folderData.id,
                "parentId": folderData.parentId,
                "name": folderData.name,
                "description": folderData.description,
                "icon": folderData.icon,
                "emoji": emoji
            });
            
            const data = response.data;
            if (data.status) {
                ToastUtil(data.message || "更新成功", '🥰', "success");
                // 发布消息更新文件夹列表
                PubSub.publish('refreshFolder', true);
                // 关闭弹窗
                onOpenChange(false);
                // 清除预览
                if (previewUrl && previewUrl.startsWith('blob:')) {
                    URL.revokeObjectURL(previewUrl);
                }
            } else {
                ToastUtil(data.message || "更新失败", '😰', "error");
            }
        } catch (error: any) {
            ToastUtil(error.message || "操作异常", '🥸', "error");
        }
    }

    // 返回组件
    return (
        <>
            <Modal backdrop={"blur"} isOpen={isOpen} onOpenChange={onOpenChange}
                placement={"auto"} size="md"
                isDismissable={false}>
                <ModalContent>
                    {
                        onClose => (
                            <>
                                <ModalHeader className={`dark:text-white light:text-black text-center`}>修改文件夹</ModalHeader>
                                <ModalBody>
                                    {loading ? (
                                        <div className="flex justify-center py-8">
                                            <Spinner label="加载中..." color="primary" />
                                        </div>
                                    ) : (
                                        <>
                                            {/* Icon */}
                                            <div className={'flex text-center justify-center items-center pb-3'}>
                                                <p className={`text-3xl shadow-sm border rounded-full p-2 cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors`}
                                                    onClick={(v) => {
                                                        onOpenSelectEmoji()
                                                    }}>{emoji}</p>
                                            </div>
                                            {/* 表单 */}
                                            <Input
                                                type="text"
                                                label="名称"
                                                placeholder="请输入文件夹名称"
                                                variant="bordered"
                                                labelPlacement="outside"
                                                color={"primary"}
                                                value={folderData.name}
                                                onValueChange={(name) => {
                                                    setFolderData({
                                                        ...folderData,
                                                        name
                                                    })
                                                }}
                                                startContent={
                                                    <BiFolderOpen
                                                        className="text-2xl text-default-400 pointer-events-none flex-shrink-0" />
                                                }
                                                isRequired
                                            />

                                            {/* 文件上传区域 */}
                                            <div className="w-full space-y-2">
                                                <p className="text-sm text-default-500">图标上传</p>

                                                {previewUrl ? (
                                                    <div className="relative w-full flex justify-center">
                                                        <div className="relative w-24 h-24 border rounded-md overflow-hidden">
                                                            <Image
                                                                src={previewUrl}
                                                                alt="Icon preview"
                                                                className="w-full h-full object-cover"
                                                            />
                                                            <Button
                                                                isIconOnly
                                                                size="sm"
                                                                color="danger"
                                                                variant="flat"
                                                                className="absolute top-1 right-1"
                                                                onClick={clearUploadedIcon}
                                                            >
                                                                <BiX />
                                                            </Button>
                                                        </div>
                                                    </div>
                                                ) : (
                                                    <div
                                                        className="w-full border-2 border-dashed border-default-200 rounded-lg p-4 flex flex-col items-center justify-center cursor-pointer hover:bg-default-100 transition-colors"
                                                        onClick={() => fileInputRef.current?.click()}
                                                    >
                                                        <BiUpload className="text-2xl text-default-400" />
                                                        <p className="text-sm text-default-500 mt-2">
                                                            {uploading ? "上传中..." : "点击上传图标（选填）"}
                                                        </p>
                                                        <input
                                                            type="file"
                                                            ref={fileInputRef}
                                                            className="hidden"
                                                            accept="image/*"
                                                            onChange={handleFileUpload}
                                                            disabled={uploading}
                                                        />
                                                    </div>
                                                )}
                                            </div>

                                            <Textarea
                                                className={"break-all dark:text-white light:text-black"}
                                                type="text"
                                                label="描述"
                                                placeholder="请输入文件夹描述（选填）"
                                                variant="bordered"
                                                labelPlacement="outside"
                                                color={"primary"}
                                                value={folderData.description}
                                                onValueChange={(description) => {
                                                    setFolderData({
                                                        ...folderData,
                                                        description
                                                    })
                                                }}
                                                startContent={
                                                    <BiLabel
                                                        className="text-2xl text-default-400 pointer-events-none flex-shrink-0" />
                                                }
                                            />
                                        </>
                                    )}
                                </ModalBody>
                                <ModalFooter className="justify-center">
                                    <Button className={"w-1/3"} color="default" variant="flat"
                                        onClick={() => onOpenChange(false)}
                                        isDisabled={loading || uploading}>
                                        取消
                                    </Button>
                                    <Button className={"w-1/3"} color="primary"
                                        onClick={updateFolder}
                                        isDisabled={!folderData.name.trim() || loading || uploading}>
                                        {uploading ? "上传中..." : "更新"}
                                    </Button>
                                </ModalFooter>
                            </>
                        )
                    }
                </ModalContent>
            </Modal>
            {/* 表情选择 */}
            <EmojiSelect isSelect={isSelectEmoji} onSelectChange={onSelectChange} setEmoji={setEmoji} />
        </>
    )
} 